/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;

/**
 *
 * @author bego
 */
@WebServlet(name = "serv1", urlPatterns = {"/serv1"})
public class serv1 extends HttpServlet {
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        //get session requested.
        HttpSession session = request.getSession(true);

        if(!request.getRequestedSessionId().equals(session.getId()) || request.getParameterMap().isEmpty()){
            out.println("<center>You have not initiated session or the session expired! <br><br>");
            out.println("<a href=\"/hw2\">Go to login page</a> <br></center>");
            session.invalidate();
        }else{  
            
            Login values = (Login) session.getAttribute("obj");
            
            if(values == null){
                values = new Login(request.getParameter("name").toString(), request.getParameter("password").toString());
                session.setAttribute("obj", values);
            }
            //set inactive interval in seconds
            session.setMaxInactiveInterval(1*60);
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);
            Integer counter = (Integer) session.getAttribute("counter");

            if(counter == null){
                counter = new Integer(1);
            }else{
                counter = new Integer(counter.intValue()+1);
            }

            if(counter==1){
                out.println("This is a new session.<BR>");
            } else {
                out.println("This is not a new session.<BR>");
            }

            session.setAttribute("counter", counter);
            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet serv1</title>");            
                out.println("</head>");
                out.println("<body>");
                out.println("<div> Data from this session   :<br/>");
                out.println("ID: "+ session.getId()+"<br/>");
                out.println("Requested Session: "+ request.getRequestedSessionId()+"<br/>");
                out.println("Entry #: "+ counter +"<br/>");
                out.println("IP: "+ request.getRemoteAddr() +"<br/>");
                out.println("Search Query: "+ request.getQueryString() +"<br/>");
                out.println("Session's inactive interval: "+ session.getMaxInactiveInterval() +" seconds<br/>");
                out.println("Creation Time: "+ formatter.format(session.getCreationTime())+"<br/>");
                out.println("Last Accesed Time: "+ formatter.format(session.getLastAccessedTime())+"<br/>");
                out.println("<H3>Some data stored in this session:</H3>");
                Enumeration e = session.getAttributeNames();
                while (e.hasMoreElements()) {
                  String name = (String) e.nextElement();
                  out.println(name + ": " + session.getAttribute(name) + "<BR>");
                }
                out.println("Username: "+values.username);
                out.println("Pass: "+values.passw);
                out.println("</div>");
                out.println("</body>");
                out.println("</html>");
            } finally {            
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
